<template>
	<div class="article-vue">
		<div ref="box" @scroll="onScroll" class="article-container">
			<!-- 文章列表 -->
			<van-pull-refresh v-model="pullLoading" @refresh="onRefresh">
				<van-list
					v-model="loading"
					:finished="finished"
					finished-text="没有更多了"
					@load="onLoad"
				>
					<van-cell
						v-for="item in list"
						:key="item.art_id"
						@click="intoArticle(item)"
					>
						<div class="title">
							{{ item.title }}
						</div>

						<van-grid :border="false" :column-num="item.cover.type">
							<van-grid-item
								v-for="(img, index) in item.cover.images"
								:key="index"
							>
								<van-image :src="img" />
							</van-grid-item>
						</van-grid>

						<div class="article-info">
							<span>{{ item.aut_name }}</span>
							<span>{{ item.comm_count }}评论</span>
							<span>{{ item.pubdate | relativeTime }}</span>
							<van-icon name="cross" />
						</div>
					</van-cell>
				</van-list>
			</van-pull-refresh>
		</div>
	</div>
</template>

<script>
import { recArticleAPI } from "@/api/articles";
export default {
	// 子组件需要父组件传文章的频道的id
	props: ["channel_id"],
	data() {
		return {
			list: [],
			loading: false,
			pullLoading: false,
			finished: false,
			timestamp: Date.now(),
			scrollTop: 0,
		};
	},
	// 当组件缓存时调用
	activated() {
		this.$refs.box.scrollTop = this.scrollTop;
	},
	methods: {
		async onLoad() {
			// 异步更新数据
			const res = await recArticleAPI({
				channel_id: this.channel_id,
				// 第一次请求，请求最新的文章
				timestamp: this.timestamp,
			});
			// 保存上一次请求的时间戳，方便下划访问历史文章
			this.timestamp = res.data.pre_timestamp;
			// 因为是往后加文章，我们用push，用赋值会覆盖前面的文章
			this.list.push(...res.data.results);
			// 加载完成，让加载状态变为false
			this.loading = false;
			// 所有都加载完成，就是当时间戳不存在时，设为完成状态，否则报错
			if (this.timestamp == null) {
				this.finished = true;
			}
		},
		async onRefresh() {
			// 异步更新数据
			const res = await recArticleAPI({
				channel_id: this.channel_id,
				// 第一次请求，请求最新的文章
				timestamp: Date.now(),
			});
			// 保存上一次请求的时间戳，方便下划访问历史文章
			this.timestamp = res.data.pre_timestamp;
			// 每次上拉都会刷新列表，因此我们应该用赋值
			this.list = res.data.results;
			// 加载完成，让加载状态变为false
			this.pullLoading = false;

			this.finished = false;
		},
		intoArticle(item) {
			/* {
				name: "myarticle",
				query: id,
			} */
			this.$router.push(`/article?id=${item.art_id}`);
		},
		onScroll() {
			this.scrollTop = this.$refs.box.scrollTop;
		},
	},
};
</script>

<style scoped lang='less'>
.article-container {
	position: fixed;
	top: 90px;
	bottom: 50px;
	width: 100vw;
	overflow: auto;
	.title {
		font-size: 18px;
	}
	.article-info {
		position: relative;
		span {
			color: #ccc;
			margin: 0 8px;
			font-size: 13px;
		}
		.van-icon {
			position: absolute;
			right: 0;
		}
	}
}
</style>
